package GUI;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.table.AbstractTableModel;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JEditorPane;
import javax.swing.JButton;
import Controller.ComplaintHandelingController;
import Controller.ComplaintSubmissionController;
import Controller.DBcontroller;
import Entity.Complaint;
import Entity.Complaint.validateErrs;
import Entity.Customer;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;
import java.util.Date;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
/**
 * this is the GUI for handling complaints from customers. the service class worker will choose a complaint and answer it.
 * @author Moran Abilea
 *
 */
public class CustomerComplaintHandelingBoundary extends JFrame {
	private JPanel contentPane;
	private JTable table;
	private JTextField DesctextField;
	private JTextField workerId;
	private JTextField compenstate;
	private Complaint myGUIw=new Complaint(null,null,0.0); // just for having a new complaint object. 
	private boolean okflag=false; // this will be a flag that will indicates to save to the DB.
	private JTextField CustomerIDText;
	private JTextField ComplaintNumText;
	private JTextField ComplaintSubmissionDateText;
	private int row;
	JFrame frame;
	JPanel lastPanel;
	public void setLastPanel (JPanel panel)
	{
		this.lastPanel=panel;
	}
	public void setFrame (JFrame frame)
	{
		this.frame=frame;
	}
	/**
	 * is the constructor. it has a table lister for choosing a row that will pure the data and he can answer it.
	 * it also compensate the customer if the worker didn't answer after 24 hrs. (compensation of 10 sh per day passed)
	 * @param complaintToHandle= a table from thr DB of the complaints to handle. 
	 */
	public CustomerComplaintHandelingBoundary(Complaint[] complaintToHandle) {
		final Complaint [] copy=complaintToHandle;
		setTitle("Complaint Handeling Window");
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setBounds(100, 100, 755, 555);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		JLabel lblCustomerComplaintsHandeling = new JLabel("Customer Complaints Handeling");
		lblCustomerComplaintsHandeling.setFont(new Font("Tahoma", Font.PLAIN, 14));
		lblCustomerComplaintsHandeling.setBounds(269, 0, 201, 37);
		contentPane.add(lblCustomerComplaintsHandeling);
		
		JScrollPane TablescrollPane = new JScrollPane();
		TablescrollPane.setBounds(412, 83, 304, 373);
		contentPane.add(TablescrollPane);
		
		table = new JTable(new handleJTable(ComplaintHandelingController.getCustomerComplaintsForHandeling(DBcontroller.getLoggedIn())));
		TablescrollPane.setViewportView(table);
		
		JLabel lblCustomerId = new JLabel("Customer Id: ");
		lblCustomerId.setBounds(28, 33, 113, 14);
		contentPane.add(lblCustomerId);
		
		JLabel lblPleaseSelectA = new JLabel("1. Please select a row in order to handel the complaint");
		lblPleaseSelectA.setBounds(412, 58, 347, 14);
		contentPane.add(lblPleaseSelectA);
		
		JLabel lblComplaintNumberauto = new JLabel("Complaint number: ");
		lblComplaintNumberauto.setBounds(27, 58, 114, 14);
		contentPane.add(lblComplaintNumberauto);
		
		JLabel lblComplaintDescription = new JLabel("Complaint Description: ");
		lblComplaintDescription.setBounds(27, 83, 222, 14);
		contentPane.add(lblComplaintDescription);
		
		// don't forget the fact the i'll need to append the text (only one line allowed here). i'll need to append or else i'll need to use HTML which i don't wanna
		final JTextArea DesctextArea = new JTextArea();
		DesctextArea.setBounds(27, 103, 332, 78);
		//DesctextArea.setLineWrap(true);
		contentPane.add(DesctextArea);
		DesctextField = new JTextField();
		DesctextField.setBounds(27, 103, 332, 78);
		contentPane.add(DesctextField);
		DesctextField.setColumns(10);
		DesctextArea.setEditable(false);
		
		JLabel lblComplaintSubmittedIn = new JLabel("Complaint Submitted in date: ");
		lblComplaintSubmittedIn.setBounds(27, 192, 201, 14);
		contentPane.add(lblComplaintSubmittedIn);
		
		JLabel longLine = new JLabel("_______________________________________________________");
		longLine.setBounds(27, 209, 374, 14);
		contentPane.add(longLine);
		
		JLabel lblEnterYourId = new JLabel("2. Enter your id:");
		lblEnterYourId.setBounds(27, 237, 107, 14);
		contentPane.add(lblEnterYourId);
		workerId = new JTextField();
		// this part will block any possibility for trying to type an id with "undigit" chars.
				workerId.addKeyListener(new KeyAdapter() {
					@Override
					public void keyTyped(KeyEvent key) {
						char c=key.getKeyChar();
						if(!(Character.isDigit(c))||c==KeyEvent.VK_BACK_SPACE|| c==KeyEvent.VK_DELETE){
							getToolkit().beep();
							key.consume();
						}
					}
				});
		workerId.setBounds(138, 234, 141, 20);
		contentPane.add(workerId);
		workerId.setColumns(10);
		
		JLabel lblYourAnsweringDate = new JLabel("Your answering date is:"+myGUIw.getDateOfAnswer());
		lblYourAnsweringDate.setBounds(27, 262, 332, 14);
		contentPane.add(lblYourAnsweringDate);
		
		JLabel lblEnterYourAnswer = new JLabel("3. Enter your answer here:");
		lblEnterYourAnswer.setBounds(27, 281, 222, 14);
		contentPane.add(lblEnterYourAnswer);
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(27, 298, 332, 61);
		contentPane.add(scrollPane);
		final JEditorPane answering = new JEditorPane();
		scrollPane.setViewportView(answering);
		
		JLabel lblEnterYourCompen = new JLabel("4. Enter your compensation here:");
		lblEnterYourCompen.setBounds(27, 365, 210, 14);
		contentPane.add(lblEnterYourCompen);
		compenstate = new JTextField();
		compenstate.setText("00.00");
		
		//******************************* this part need to be changed. it checks about the 24 hours condition.
		Date test=new Date(113,11,30,12,0,0);
		double conditionalCompenstate = 0;
		// if the answer is inside the 24 hours then the system won't compensate.
		if(myGUIw.getDateOfAnswer().getDay()==test.getDay()||(myGUIw.getDateOfAnswer().getDay()==(test.getDay()+1)&&(myGUIw.getDateOfAnswer().getHours()<test.getHours())))
			conditionalCompenstate=0;
		// else, we need to compensate 10 shackles multiply the "time" passed.
		else if(myGUIw.getDateOfAnswer().after(test)){
			long howmany=daysDiff(test,myGUIw.getDateOfAnswer());
			conditionalCompenstate=10*howmany; 
			compenstate.setText(Double.toString(conditionalCompenstate));
			compenstate.setEditable(false);
		}
		//*********************************************************************************	
		
		// this part will block any possibility for trying to type an id with "undigit" chars.
				compenstate.addKeyListener(new KeyAdapter() {
					@Override
					public void keyTyped(KeyEvent key) {
						char c=key.getKeyChar();
						if(!(Character.isDigit(c))||c==KeyEvent.VK_BACK_SPACE|| c==KeyEvent.VK_DELETE||c==KeyEvent.VK_MINUS)
							if(c==KeyEvent.VK_PERIOD)return;
							else if(c==KeyEvent.VK_MINUS||!(Character.isDigit(c))){
								getToolkit().beep();
								key.consume();}
						}
				});
		compenstate.setBounds(247, 362, 112, 20);
		contentPane.add(compenstate);
		compenstate.setColumns(10);
		
		JButton btnSaveYourResponce = new JButton("Save your responce");
		btnSaveYourResponce.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				myGUIw.setWorker_id(workerId.getText());// getting the id text from the worker.
				myGUIw.setResult(" "+answering.getText());// getting the answer text from the worker.
				myGUIw.setCompensation(Double.parseDouble(compenstate.getText())); // getting the compensation from the worker.
				if(myGUIw.wvalidate()==validateErrs.IDERR){ // if the user entered less then 9 digits, throw  error pop up. 
					JOptionPane errid=new JOptionPane();
					String erridmsg="You entered an invalid id:"+workerId.getText()+"\nPlease enter a 9 digits id.";
					errid.setMessage(erridmsg);
					errid.setMessageType(JOptionPane.ERROR_MESSAGE);
					JDialog iddidalog=errid.createDialog(null,"Error! Wrong id.");
					iddidalog.setVisible(true);
				} 
				else if(myGUIw.wvalidate()==validateErrs.RESERR){ // if the user didn't enter any description, throw  error pop up. 
					JOptionPane errid=new JOptionPane();
					String erridmsg="You didn't enter any answer \n Please enter a description.";
					errid.setMessage(erridmsg);
					errid.setMessageType(JOptionPane.ERROR_MESSAGE);
					JDialog iddidalog=errid.createDialog(null,"Error! Needed answer.");
					iddidalog.setVisible(true);
				} 
				else if(myGUIw.wvalidate()==null){ // else, throw a good pop up.
					JOptionPane errid=new JOptionPane(); 
					String okidmsg="You finished entering your answering. now sending...";
					errid.setMessage(okidmsg);
					errid.setMessageType(JOptionPane.INFORMATION_MESSAGE);
					JDialog iddidalog=errid.createDialog(null,"Sending...");
					iddidalog.setVisible(true);
					okflag=true;
				}
			}
		});
		// if everything went well, save to the DB.
		if(okflag){
			myGUIw.setHandled(true); // before saving set the flag to true (so that the DB won't show it again to handle).
			myGUIw.save();
			// in this part of the code we will add the compensation (even if it is zero) to the account of the customer.
			Customer[] c=DBcontroller.getCustomers();
			for(int i=0;i<c.length;i++)
				if(c[i].getcustomer_id().equals(copy[row].getCustomer_id()))
					c[i].AddBalance(copy[row].getCompensation());
		}
		btnSaveYourResponce.setBounds(27, 413, 171, 23);
		contentPane.add(btnSaveYourResponce);
		
		JButton btnCancelgoBack = new JButton("Cancel/Go back");
		btnCancelgoBack.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				close();
				frame.setContentPane(lastPanel);
				frame.setVisible(true);
			}
		});
		btnCancelgoBack.setBounds(260, 413, 141, 23);
		contentPane.add(btnCancelgoBack);
		
		JLabel lblIfYouWant = new JLabel("if you want to cancel");
		lblIfYouWant.setBounds(270, 442, 141, 14);
		contentPane.add(lblIfYouWant);
		
		JLabel lblAfterSavingAlso = new JLabel("after saving, also click \"go back\"");
		lblAfterSavingAlso.setBounds(27, 442, 222, 14);
		contentPane.add(lblAfterSavingAlso);
		
		JLabel lblNoteIfYou = new JLabel("Note: not answering this complaint within 24 hours, will auto compensate the customer with 10 sh per delay in days.");
		lblNoteIfYou.setBounds(27, 480, 702, 14);
		contentPane.add(lblNoteIfYou);
		
		// handle the functionality for clicking the row and "pour" it into Jtextfields.
		table.addMouseListener(new MouseAdapter() {
			  public void mouseClicked(MouseEvent e) {
			    if (e.getClickCount() == 2) {
			      JTable target = (JTable)e.getSource();
			      int row = target.getSelectedRow();
			      CustomerIDText.setText(copy[row].getCustomer_id());
			      ComplaintNumText.setText(Integer.toString(copy[row].getComplaint_number()));
			      // start splitting the description to rows.
			      String [] splited=copy[row].getDescription().split("\n"); 
			      for (int s = 0; s < splited.length; s++)  
			      {  
			    	  DesctextArea.append(splited[s]);  
			    	  DesctextArea.append("\n");  
			      } 
			      // end of split
			      ComplaintSubmissionDateText.setText(copy[row].getDateOfsubmission().toString());
			    }
			  }
		});
		
		CustomerIDText = new JTextField();
		CustomerIDText.setBounds(151, 30, 86, 20);
		contentPane.add(CustomerIDText);
		CustomerIDText.setColumns(10);
		CustomerIDText.setEditable(false);
		
		ComplaintNumText = new JTextField();
		ComplaintNumText.setBounds(151, 55, 86, 20);
		contentPane.add(ComplaintNumText);
		ComplaintNumText.setColumns(10);
		ComplaintNumText.setEditable(false);
		
		ComplaintSubmissionDateText = new JTextField();
		ComplaintSubmissionDateText.setBounds(192, 189, 167, 20);
		contentPane.add(ComplaintSubmissionDateText);
		ComplaintSubmissionDateText.setColumns(10);
		ComplaintSubmissionDateText.setEditable(false);
	}
	
	public static long daysDiff(Date from, Date to) {
	    return daysDiff(from.getTime(), to.getTime());
	}

	public static long daysDiff(long from, long to) {
	    return Math.round( (to - from) / 86400000D ); // 1000 * 60 * 60 * 24
	}
	public void close()
	{
		WindowEvent windowclose=new WindowEvent(this,WindowEvent.WINDOW_CLOSING);
		Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(windowclose);
	}
}

class handleJTable extends AbstractTableModel
{
	String[] titles={"Complaint Num","Customer ID","Submitssion Date","Description"};
	Object[][] data;
	
	public handleJTable(Complaint[] c)
	{
		super();
		this.data=new Object[c.length][4];
		for(int i=0; i<c.length; i++)
		{
			this.data[i][0]=c[i].getComplaint_number();
			this.data[i][1]=c[i].getCustomer_id();
			this.data[i][2]=c[i].getDateOfSubmition();
			this.data[i][3]=c[i].getDescription();
		}
	}
	// override the other function.
	@Override
	public int getColumnCount() {return this.titles.length;}

	@Override
	public int getRowCount() {return data.length;}

	@Override
	public Object getValueAt(int arg0, int arg1) {return data[arg0][arg1];}
	
	@Override
	public String getColumnName(int column) {return (String) this.titles[column];}
}